package com.wy._02io.fileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CompressUtil {
    // 为了保持目录结构，所以加一层。
    public static void compressFolder(String folderPath, String zipFilePath){
        File file = new File(folderPath);
        String fileName = file.getName();
        compressFolder(folderPath,zipFilePath,fileName+"/");
    }

    public static void compressFolder(String folderPath, String zipFilePath, String prefix) {
        ZipOutputStream zipOutputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(zipFilePath);
            zipOutputStream = new ZipOutputStream(fileOutputStream);

            File folder = new File(folderPath);
            addFolderToZip(prefix, folder, zipOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (zipOutputStream != null) {
                    zipOutputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void addFolderToZip(String prefix, File folder, ZipOutputStream zipOutputStream) throws IOException {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    addFolderToZip(prefix + file.getName() + "/", file, zipOutputStream);
                } else {
                    ZipEntry zipEntry = new ZipEntry(prefix + file.getName());
                    zipOutputStream.putNextEntry(zipEntry);

                    FileInputStream fileInputStream = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fileInputStream.read(bytes)) >= 0) {
                        zipOutputStream.write(bytes, 0, length);
                    }
                    fileInputStream.close();
                    zipOutputStream.closeEntry();
                }
            }
        }
    }
}
